#!/usr/bin/env node

import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 修复Java版本的函数
function fixJavaVersion() {
    console.log('🔧 Fixing Java version...');
    
    const filesToFix = [
        'android/app/capacitor.build.gradle',
        'android/capacitor-cordova-android-plugins/build.gradle'
    ];
    
    let fixedCount = 0;
    
    filesToFix.forEach(filePath => {
        const fullPath = path.join(__dirname, filePath);
        
        if (fs.existsSync(fullPath)) {
            let content = fs.readFileSync(fullPath, 'utf8');
            
            // 替换Java 21为Java 17
            const originalContent = content;
            content = content.replace(/JavaVersion\.VERSION_21/g, 'JavaVersion.VERSION_17');
            
            if (content !== originalContent) {
                fs.writeFileSync(fullPath, content);
                console.log(`✅ Fixed Java version in ${filePath}`);
                fixedCount++;
            }
        }
    });
    
    if (fixedCount > 0) {
        console.log(`🎉 Fixed Java version in ${fixedCount} file(s)`);
    } else {
        console.log('✅ All Java versions are already correct');
    }
}

// 构建并运行Android应用
function buildAndRunAndroid() {
    try {
        console.log('🚀 Building and running Android app...');
        
        // 1. 修复Java版本
        fixJavaVersion();
        
        // 2. 进入Android目录
        process.chdir(path.join(__dirname, 'android'));
        
        // 3. 构建APK
        console.log('📦 Building APK...');
        execSync('.\\gradlew assembleDebug', { stdio: 'inherit' });
        
        console.log('🎉 Android APK built successfully!');
        console.log('📱 APK location: android/app/build/outputs/apk/debug/app-debug.apk');
        
        // 4. 尝试安装到设备（可选）
        try {
            console.log('📱 Attempting to install APK to device...');
            execSync('.\\gradlew installDebug', { stdio: 'inherit' });
            console.log('✅ APK installed successfully!');
        } catch (error) {
            console.log('⚠️  No device connected. APK is ready for manual installation.');
            console.log('📱 To install manually:');
            console.log('   1. Connect an Android device or start an emulator');
            console.log('   2. Run: adb install android/app/build/outputs/apk/debug/app-debug.apk');
        }
        
    } catch (error) {
        console.error('❌ Failed to build/run Android app:', error.message);
        process.exit(1);
    }
}

// 主函数
function main() {
    console.log('🎯 Starting Android build and run with Java version fix...');
    buildAndRunAndroid();
}

// 运行主函数
main();
